<template>
  <div class="app-container">
    <!--景区搜索区块-->
    <el-form :model="queryParams" :inline="true" ref="queryForm" size="small" v-show="showSearch">
      <el-form-item label="景区名称" prop="scenicName">
        <el-input
          v-model="queryParams.scenicName"
          clearable
          placeholder="请输入景区名称(含关键字)"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="景区状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!--    显示或隐藏景区搜索区块-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:scenic:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-sort"
          size="mini"
          @click="toggleExpandAll"
        >展开/折叠
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList" :columns="columns"></right-toolbar>
    </el-row>

    <!--景区列表区块-->
    <el-table
      v-if="refreshTable"
      v-loading="loading"
      :data="scenicList"
      row-key="scenicId"
      :default-expand-all="isExpandAll"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
    >
      <el-table-column key="scenicId" prop="scenicId" label="景区ID" v-if="columns[0].visible" fixed="left"
                       width="100"></el-table-column>
      <el-table-column key="scenicShortName" prop="scenicShortName" label="景区简称" v-if="columns[1].visible"
                       width="120"></el-table-column>
      <el-table-column key="scenicName" prop="scenicName" label="景区全称" v-if="columns[2].visible"
                       width="200"></el-table-column>
      <el-table-column key="status" prop="status" label="状态" v-if="columns[3].visible" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column key="wharfNum" prop="wharfNum" label="码头数量" align="center"
                       width="50"></el-table-column>
      <el-table-column key="boatNum" prop="boatNum" label="船只数量" align="center"
                       width="50"></el-table-column>
      <el-table-column key="city" prop="city" label="所在城市" v-if="columns[4].visible" width="80"
                       align="center"></el-table-column>
      <el-table-column key="leader" prop="leader" label="负责人" v-if="columns[5].visible" align="center"
                       width="80"></el-table-column>
      <el-table-column key="phone" prop="phone" label="联系电话" v-if="columns[6].visible" align="center"
                       width="110"></el-table-column>
      <el-table-column key="address" prop="address" label="详细地址" v-if="columns[7].visible" align="center"
                       width="280"></el-table-column>
      <el-table-column key="createBy" label="创建者" align="center" prop="createBy" v-if="columns[8].visible"
                       width="80"></el-table-column>
      <el-table-column key="createTime" label="创建时间" align="center" prop="createTime" v-if="columns[9].visible"
                       width="150">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" min-width="120" fixed="right">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.scenicId !== 100"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:scenic:edit']"
          >编辑基本信息
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-location-information"
            @click="enterBoatMonitorView(scope.row)"
            v-hasPermi="['system:scenic:edit']"
            v-if="scope.row.parentId !== 0&&scope.row.scenicId !== 101"
          >监控中心
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit-outline"
            @click="handleFenceEdit(scope.row)"
            v-hasPermi="['system:fence:edit']"
            v-if="scope.row.parentId !== 0&&scope.row.scenicId !== 101"
          >绘制码头、电子围栏等
          </el-button>
          <el-button
            v-if="scope.row.scenicId === 100"
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['system:scenic:add']"
          >新增
          </el-button>
          <el-button
            v-if="scope.row.parentId !== 0&&scope.row.scenicId !== 101"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:scenic:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改景区对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="900px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="140px" label-position="center">
        <el-row>
          <el-col :span="24" v-if="form.parentId !== 0">
            <el-form-item label="上级景区：" prop="parentId">
              <treeselect v-model="form.parentId" :options="scenicOptions" :normalizer="normalizer"
                          placeholder="选择上级景区"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="景区简称：" prop="scenicShortName">
              <el-input v-model="form.scenicShortName" placeholder="请输入景区名称简称(要求3~5个汉字)"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="景区全称：" prop="scenicName">
              <el-input v-model="form.scenicName" placeholder="请输入景区名称全称" maxlength="60"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="景区地址：" prop="address">
              <el-input v-model="form.address" placeholder="请输入景区详细地址" maxlength="60"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="景区所在城市：" prop="city" required>
              <el-input v-model="form.city" placeholder="请输入景区所在城市，示例：武汉市。"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="景区负责人：" prop="leader" required>
              <el-input v-model="form.leader" placeholder="请输入景区负责人姓名" maxlength="20"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="负责人联系电话：" prop="phone" required>
              <el-input v-model="form.phone" placeholder="请输入负责人联系电话" maxlength="11"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人邮箱：" prop="email" required>
              <el-input v-model="form.email" placeholder="请输入负责人邮箱" maxlength="50"/>
            </el-form-item>
          </el-col>
        </el-row>
        <!--        <el-row>-->
        <!--          <el-col :span="10">-->
        <!--            <el-form-item label="码头名称：" prop="wharfName" required>-->
        <!--              <el-input v-model="form.wharfName" placeholder="请输入码头名称" maxlength="60"/>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
        <!--        <el-form-item required>-->
        <!--          <span slot="label">-->
        <!--                码头坐标-->
        <!--                <el-tooltip placement="top">-->
        <!--                  <div slot="content">-->
        <!--                    如果输入的是百度地图格式坐标则需勾选"百度地图坐标"，如果输入的是真实的gps坐标则取消勾选。-->
        <!--                  </div>-->
        <!--                  <i class="el-icon-question"></i>-->
        <!--                </el-tooltip>-->
        <!--                ：-->
        <!--              </span>-->
        <!--          <el-row type="flex">-->
        <!--            <el-col :span="8">-->
        <!--              <el-form-item prop="wharfLat" required>-->
        <!--                <el-input v-model="form.wharfLat" placeholder="纬度。示例：30.495493"></el-input>-->
        <!--              </el-form-item>-->
        <!--            </el-col>-->
        <!--            <el-col :span="1">——</el-col>-->
        <!--            <el-col :span="8">-->
        <!--              <el-form-item prop="wharfLng" required>-->
        <!--                <el-input v-model="form.wharfLng" placeholder="经度。示例：114.34014"></el-input>-->
        <!--              </el-form-item>-->
        <!--            </el-col>-->
        <!--            <el-col :span="3">-->
        <!--              <el-checkbox v-model="isBdCoordinateSelected" style="margin-left: 20px">百度地图坐标</el-checkbox>-->
        <!--            </el-col>-->
        <!--          </el-row>-->
        <!--        </el-form-item>-->
        <!--        <el-row>-->
        <!--          <el-col :span="12">-->
        <!--            <el-form-item prop="heading" required>-->
        <!--              <span slot="label">-->
        <!--                泊位朝向-->
        <!--                <el-tooltip placement="top">-->
        <!--                  <div slot="content">-->
        <!--                    即船头朝向与正北方向的夹角，范围0~360°-->
        <!--                  </div>-->
        <!--                  <i class="el-icon-question"></i>-->
        <!--                </el-tooltip>-->
        <!--                ：-->
        <!--              </span>-->

        <!--              <el-input v-model.number="form.heading" placeholder="请输入码头泊位朝向" maxlength="60"/>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
        <!--        <el-row>-->
        <!--          <el-col :span="16">-->
        <!--            <el-form-item label="电子围栏两固定点间直线距离(单位：米)：" prop="toFixedPointsDistance" required-->
        <!--                          label-width="300px">-->
        <!--              <el-input v-model.number="form.toFixedPointsDistance" placeholder="请输入正整数值" maxlength="60"/>-->
        <!--            </el-form-item>-->
        <!--          </el-col>-->
        <!--        </el-row>-->
        <el-row>
          <el-col :span="12">
            <el-form-item label="景区状态">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in dict.type.sys_normal_disable"
                  :key="dict.value"
                  :label="dict.value"
                >{{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {addScenic, delScenic, getScenic, listScenic, listScenicExcludeChild, updateScenic} from '@/api/system/scenic'
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {bd09towgs84, wgs84tobd09} from "@/utils/gps";

export default {
  name: "Scenic",
  dicts: ['sys_normal_disable'],
  components: {Treeselect},
  data() {
    return {
      // 遮罩层
      loading: false,
      // 重新渲染表格状态
      refreshTable: true,
      // 显示搜索条件
      showSearch: true,
      // 列信息
      columns: [
        {key: 0, label: `景区ID`, visible: true},
        {key: 1, label: `景区简称`, visible: true},
        {key: 2, label: `景区全称`, visible: true},
        {key: 3, label: `状态`, visible: true},
        {key: 4, label: `所在城市`, visible: true},
        {key: 5, label: `负责人`, visible: true},
        {key: 6, label: `联系电话`, visible: true},
        {key: 7, label: `详细地址`, visible: true},
        {key: 8, label: `创建人`, visible: true},
        {key: 9, label: `创建时间`, visible: true},
      ],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 表单参数
      form: {
        parentId: 100,
      },
      // 表单校验
      rules: {
        parentId: [
          {required: true, message: "上级景区不能为空", trigger: "blur"}
        ],
        scenicShortName: [
          {required: true, message: "景区简称不能为空", trigger: "blur"},
          { min: 3, max: 8, message: '景区简称长度在3到8个字符', trigger: 'blur' }
        ],
        scenicName: [
          {required: true, message: "景区名称不能为空", trigger: "blur"}
        ],
        address: [
          {required: true, message: "景区地址不能为空", trigger: "blur"}
        ],
        email: [
          {required: true, message: "景区负责人邮箱不能为空", trigger: "blur"},
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"]
          }
        ],
        phone: [
          {required: true, message: "景区负责人联系电话不能为空", trigger: "blur"},
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: "请输入正确的手机号码",
            trigger: "blur"
          }
        ],
        city: [
          {required: true, message: "景区所在城市不能为空", trigger: "blur"}
        ],
        leader: [
          {required: true, message: "景区负责人姓名不能为空", trigger: "blur"}
        ],
      },
      // 表格树数据
      scenicList: [],
      // 景区树选项
      scenicOptions: [],
      //查询参数
      queryParams: {
        scenicName: undefined,
        scenicStatus: undefined
      },
      isBdCoordinateSelected: true, //是否勾选了"百度地图坐标"
    }
  },
  created() {
    this.getList();
  },
  methods: {
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      // console.log("handleAdd row= ", typeof row)
      // console.log("handleAdd row= ", row instanceof PointerEvent)

      if (!(row instanceof PointerEvent)) { //handleAdd方法有传参
        this.form.parentId = row.scenicId;
      } else {
        this.form.parentId = 100
      }

      this.open = true;
      this.title = "添加景区";
      listScenic().then(res => {
        // this.scenicOptions = [{
        //   scenicId: 0,
        //   scenicName: '无',
        //   children: []
        // }].concat(this.handleTree(res.data, "scenicId"));
        this.scenicOptions = this.handleTree(res.data, "scenicId");
      });
    },
    /** 展开/折叠操作 */
    toggleExpandAll() {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 查询景区列表 */
    getList() {
      this.loading = true;
      listScenic(this.queryParams).then(res => {
        this.scenicList = this.handleTree(res.data, "scenicId");
        console.log("this.scenicList: ", this.scenicList)
        this.loading = false;
      })
    },
    /** 转换部门数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.scenicId,
        label: node.scenicName,
        children: node.children
      };
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.scenicId != undefined) {
            updateScenic(this.form).then(res => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            let wharfLat = Number(this.form.wharfLat);
            let wharfLng = Number(this.form.wharfLng);
            this.form.wharfLat = wharfLat;
            this.form.wharfLng = wharfLng;

            //判断当前输入的码头坐标是否是百度地图格式的，如果是的则需先将其转成真实坐标，如果不是百度地图坐标则默认为是真实坐标，无需转换.
            if (this.isBdCoordinateSelected) {
              let translatedPoint = bd09towgs84(wharfLng, wharfLat);
              wharfLng = translatedPoint[0];
              wharfLat = translatedPoint[1];
            }

            let heading = this.form.heading;
            let distance = this.form.toFixedPointsDistance / 2;

            let intermediateLatLng = this.getLatLng_PDH(wharfLat, wharfLng, 20, heading + 180 >= 360 ? heading + 180 - 360 : heading + 180);
            // console.log("intermediateLatLng: ", intermediateLatLng)
            let startPointLatLng = this.getLatLng_PDH(intermediateLatLng[0], intermediateLatLng[1], distance, heading + 90 >= 360 ? heading + 90 - 360 : heading + 90);
            let endPointLatLng = this.getLatLng_PDH(intermediateLatLng[0], intermediateLatLng[1], distance, heading - 90 <= 0 ? heading - 90 + 360 : heading - 90);

            let translatedStartPointBdLatLng = wgs84tobd09(startPointLatLng[1], startPointLatLng[0]);
            let translatedEndPointBdLatLng = wgs84tobd09(endPointLatLng[1], endPointLatLng[0]);

            let toFixedPointsCoordinatesArr = [];
            let toFixedPointsBdCoordinatesArr = [];
            toFixedPointsCoordinatesArr.push(this.formatCoord(startPointLatLng[0]), this.formatCoord(startPointLatLng[1]),
              this.formatCoord(endPointLatLng[0]), this.formatCoord(endPointLatLng[1]))
            toFixedPointsBdCoordinatesArr.push(this.formatCoord(translatedStartPointBdLatLng[1]), this.formatCoord(translatedStartPointBdLatLng[0]),
              this.formatCoord(translatedEndPointBdLatLng[1]), this.formatCoord(translatedEndPointBdLatLng[0]));

            this.form.toFixedPointsCoordinates = toFixedPointsCoordinatesArr.join(",");
            this.form.toFixedPointsBdCoordinates = toFixedPointsBdCoordinatesArr.join(",");

            console.log("this.form: ", this.form)

            addScenic(this.form).then(res => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        scenicId: undefined,
        parentId: undefined,
        scenicShortName: undefined,
        scenicName: undefined,
        leader: undefined,
        phone: undefined,
        email: undefined,
        status: "0",
        city: undefined
      };
      // this.resetForm("form");
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      getScenic(row.scenicId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改景区基本信息：";
        listScenicExcludeChild(row.scenicId).then(res => {
          // this.scenicOptions = [{
          //   scenicId: 0,
          //   scenicName: '无',
          //   children: []
          // }].concat(this.handleTree(res.data, "scenicId"));

          this.scenicOptions = this.handleTree(res.data, "scenicId");
          if (this.scenicOptions.length == 0) {
            const noResultsOptions = {scenicId: this.form.parentId, scenicName: this.form.parentName, children: []};
            this.scenicOptions.push(noResultsOptions);
          }
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除名称为"' + row.scenicName + '"的数据项？').then(function () {
        return delScenic(row.scenicId);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    enterBoatMonitorView(row) {
      let page = this.$router.resolve({
        path: '/boat_monitor',
        query: {
          scenicId: row.scenicId
        }
        // params: {
        //   scenicId: row.scenicId
        // }
      })

      console.log("page.href: ", page.href)
      window.open(page.href, '_blank') //在新的页面打开
    },
    handleFenceEdit(row) {
      console.log("handleFenceEdit row: ", row)
      this.$router.push({
        // path: "/system/fenceEdit/index",
        name: "FenceEdit",
        params: {
          scenic: row
        }
      })
    },
    getLatLng_PDH(startLat, startLng, distance, heading) {
      const Earth_Radius = 6378137; //地球半径，单位：米。
      const PI_Constant = 3.1415926; //π的值
      let c = distance / Earth_Radius;
      let a = Math.acos(Math.cos(PI_Constant * (90 - startLat) / 180.0) * Math.cos(c)
        + Math.sin(PI_Constant * (90 - startLat) / 180.0) * Math.sin(c) * Math.cos(PI_Constant * (heading) / 180.0));
      let x = Math.asin(Math.sin(c) * Math.sin(PI_Constant * (heading) / 180.0) / Math.sin(a));
      console.log("getLatLng_PDH: ", c, a, x)

      let resultLat = 90.0 - a * 180.0 / PI_Constant;
      let resultLng = startLng + x * 180.0 / PI_Constant;
      return [resultLat, resultLng];
    },
    formatCoord(coordinate) {
      return Math.round(coordinate * 1000000) / 1000000;
    }
  }

}
</script>

<style scoped>

</style>
